package com.example.tellwin.mine.presenter;

import android.text.TextUtils;

import com.example.tellwin.AppHelper;
import com.example.tellwin.MainApplication;
import com.example.tellwin.api.TwjfApi;
import com.example.tellwin.base.RxPresenter;
import com.example.tellwin.base.SimpleCallback;
import com.example.tellwin.common.Common;
import com.example.tellwin.mine.bean.UserBean;
import com.example.tellwin.mine.contract.LoginRegisterContract;
import com.example.tellwin.utils.HttpUtils;

import javax.inject.Inject;

import okhttp3.RequestBody;

/**
 * @author : LinZePeng
 * @date : 2020/11/24
 * @Describe ：
 **/
public class LoginRegisterPresenter extends RxPresenter<LoginRegisterContract.View> implements LoginRegisterContract.Presenter<LoginRegisterContract.View> {

    private TwjfApi mApi;

    @Inject
    public LoginRegisterPresenter(TwjfApi mApi) {
        this.mApi = mApi;
    }

    @Override
    public void login(String phone, String verificationCode) {
        RequestBody requestBody = HttpUtils.getRequestBody("mobile", phone, "code", verificationCode);
        mApi.login(requestBody, new SimpleCallback<UserBean>(mView) {

            @Override
            public void onSuccess(UserBean userBean) {
                AppHelper.getInstance().saveUser(userBean, MainApplication.getContext());
                MainApplication.Identity = AppHelper.getInstance().isAnswer() ? Common.ANSWER : Common.NORMAL;
                mView.loginResult(userBean);
            }

            @Override
            public void onFail(String msg) {

            }
        });
    }

    @Override
    public void getVerificationCode(String phone, int type) {
        RequestBody requestBody = HttpUtils.getRequestBody("mobile", phone, "type", type + "");
        mApi.getVerificationCode(requestBody, new SimpleCallback<Object>(mView) {
            @Override
            public void onSuccess(Object o) {

            }

            @Override
            public void onFail(String msg) {

            }
        });
    }

    @Override
    public void register(String phone, String verificationCode , String invitationCode) {
        RequestBody requestBody;
        if(TextUtils.isEmpty(invitationCode)){
            requestBody = HttpUtils.getRequestBody("mobile", phone, "code", verificationCode);
        }else {
            requestBody = HttpUtils.getRequestBody("mobile", phone, "code", verificationCode, "inviteCode" , invitationCode);
        }
        mApi.register(requestBody, new SimpleCallback<UserBean>(mView) {

            @Override
            public void onSuccess(UserBean userBean) {
                AppHelper.getInstance().saveUser(userBean, MainApplication.getContext());
                MainApplication.Identity = AppHelper.getInstance().isAnswer() ? Common.ANSWER : Common.NORMAL;
                mView.registerResult(userBean);
            }

            @Override
            public void onFail(String msg) {

            }
        });
    }
}
